package com.jxzyk.model.course;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.core.entity.I_List;
import com.core.ui.fragment.BaseFragment;
import com.core.util.T;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.State;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.extras.SoundPullEventListener;
import com.jxzyk.App;
import com.jxzyk.R;
import com.jxzyk.adapter.CourseAdapter;
import com.jxzyk.config.API;
import com.jxzyk.entity.Course;
import com.jxzyk.entity.CourseType;
import com.jxzyk.http.BaseRequest.OnDialogListener;
import com.jxzyk.http.Query;
import com.jxzyk.http.req.CourseRequest;
import com.jxzyk.model.MainActivity;
import com.jxzyk.model.SearchActivity;
import com.jxzyk.view.TitleLayout;
import com.jxzyk.view.TitleLayout.OnPopupWindowListener;
import com.lidroid.xutils.view.annotation.ViewInject;

public class CourseFragment extends BaseFragment {
	@ViewInject(R.id.title)
	TitleLayout title;
	@ViewInject(R.id.list_course)
	PullToRefreshListView mPullRefreshListView;

	private ListView listView;

	@Override
	public void initData(Bundle bundle) {

	}

	@Override
	public int initUiRes() {
		return R.layout.fra_course;
	}

	@Override
	public void initUi(View view) {
		try {
			initTitle();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		/**
		 * Add Sound Event Listener
		 */
		// SoundPullEventListener<ListView> soundListener = new
		// SoundPullEventListener<ListView>(
		// getActivity());
		// soundListener.addSoundEvent(State.PULL_TO_REFRESH, R.raw.pull_event);
		// soundListener.addSoundEvent(State.RESET, R.raw.reset_sound);
		// soundListener.addSoundEvent(State.REFRESHING,
		// R.raw.refreshing_sound);
		// mPullRefreshListView.setOnPullEventListener(soundListener);
		// Set a listener to be invoked when the list should be refreshed.
		mPullRefreshListView
				.setOnRefreshListener(new OnRefreshListener<ListView>() {
					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {
						String label = DateUtils.formatDateTime(getActivity()
								.getApplicationContext(), System
								.currentTimeMillis(),
								DateUtils.FORMAT_SHOW_TIME
										| DateUtils.FORMAT_SHOW_DATE
										| DateUtils.FORMAT_ABBREV_ALL);
						// Update the LastUpdatedLabel
						refreshView.getLoadingLayoutProxy()
								.setLastUpdatedLabel(label);
						loadList(0);
					}
				});
		// Add an end-of-list listener
		mPullRefreshListView
				.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

					@Override
					public void onLastItemVisible() {
						loadList(page);
					}
				});
		listView = mPullRefreshListView.getRefreshableView();
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Bundle bundle = new Bundle();
				try {
					Course course = (Course) adapter.getLists().get(arg2 - 1);
					bundle.putSerializable(course.getClass().getName(), course);
					showActivity(CourseActivity.class, bundle);
				} catch (Exception e) {
					e.printStackTrace();
					T.toast("下标越界[listsize]" + lists.size() + "[index]" + arg2);
				}
			}
		});
		loadList(page);
	}

	private void initTitle() throws Exception {
		title.setTtile("最热课程");
		// 加载数据
		List<String> groups = new ArrayList<String>();
		final List<I_List> data = new ArrayList<>();
		CourseType courseType = new CourseType();
		courseType.setType_name("最热课程");
		courseType.setType_id(null);
		data.add(courseType);
		data.addAll(App.getCourseType());
		for (int i = 0; i < data.size(); i++) {
			CourseType type = (CourseType) data.get(i);
			groups.add(type.getType_name());
		}
		title.setPopupWindowListener(groups, new OnPopupWindowListener() {

			@Override
			public void onClick(int position) {
				CourseType courseType = (CourseType) data.get(position);
				type = courseType.getType_id();
				title.setTtile(courseType.getType_name());
				loadList(0);
			}
		});
		title.setSearchListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Bundle bundle = new Bundle();
				bundle.putString(SearchActivity.class.getName(),
						API.Course.getCourses);
				showActivity(SearchActivity.class, bundle);
			}
		});
	}

	public static CourseType courseType = null;

	@Override
	public void onResume() {
		super.onResume();
		if (courseType != null) {
			type = courseType.getType_id();
			title.setTtile(courseType.getType_name());
			loadList(0);
			courseType = null;
		}

	}

	private List<I_List> lists = new ArrayList<>();
	private CourseAdapter adapter = null;
	private static String type = null;
	private int page = 0;

	private void loadList(int my_page) {
		CourseRequest request = new CourseRequest(getActivity(),
				API.Course.getCourses);
		Query query = new Query();
		query.setPage(my_page);
		query.setLength(5);
		request.setType(type);
		request.setQuery(query);
		if (my_page == 0) {
			page = my_page;
			lists.clear();
			if (adapter == null) {
				adapter = (CourseAdapter) new CourseAdapter().instance(
						getActivity(), lists);
				listView.setAdapter(adapter);
			}
		}
		request.setOnDialogListener(new OnDialogListener() {

			@Override
			public void onSuccess(JSONObject json) {
				try {
					JSONArray array = json.getJSONArray("data");
					if (array.size() > 0) {
						for (int i = 0; i < array.size(); i++) {
							Course course = (Course) new Course()
									.instance(array.getJSONObject(i));
							lists.add(course);
						}
						adapter.notifyDataSetChanged();
						page++;
					}
					// Call onRefreshComplete when the list has been refreshed.
					mPullRefreshListView.onRefreshComplete();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(String msg) {
				// Call onRefreshComplete when the list has been refreshed.
				adapter.notifyDataSetChanged();
				mPullRefreshListView.onRefreshComplete();
				// if (page == 0) {
				// T.toast("数据为空");
				// }
			}
		});
		if (page == 0) {
			request.show();
		} else {
			request.start();
		}
	}
}
